import { AfterViewInit, Component, Inject, OnInit, Optional, ViewChild } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { ReuseTabService } from '@delon/abc/reuse-tab';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { SFComponent, SFSchema, SFTextareaWidgetSchema, SFTextWidgetSchema, SFUISchema } from '@delon/form';
import { SettingsService } from '@delon/theme';
import { CaptchaComponent } from 'src/app/shared/components/captcha';

import { AccountService } from '../../services/account.service';

@Component({
  selector: 'app-account-components-edit-password',
  templateUrl: './edit-paypassword.component.html',
  styleUrls: ['./edit-paypassword.component.less'],
})
export class AccountComponentsEditPayPasswordComponent implements OnInit, AfterViewInit {
  @ViewChild('dun', { static: false })
  private dun!: CaptchaComponent;

  step: 0 | 1 | 2 = 0;

  step1Schema!: SFSchema;
  ui!: SFUISchema;
  @ViewChild('step1sf', { static: false })
  step1sf!: SFComponent;

  phone: string;

  formGroup3!: FormGroup;
  confirmPasswordValidator!: ValidatorFn;

  isShowPwd = false;
  isShowConfirmPwd = false;

  count = 0;
  interval$: any;

  constructor(
    private fb: FormBuilder,
    public service: AccountService,
    private route: ActivatedRoute,
    private settingService: SettingsService,
    private router: Router,
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Optional()
    @Inject(DA_SERVICE_TOKEN)
    private tokenService: ITokenService,
  ) {
    this.phone = route.snapshot.queryParams.phone;
  }

  ngAfterViewInit(): void {
    this.dun.init();
  }

  ngOnInit() {
    if (this.phone) {
      this.initStep1SF();
    } else {
      this.service.http.post(this.service.$api_get_current_user_info).subscribe((res) => {
        if (res) {
          this.phone = res.data?.phone;
          this.initStep1SF();
        }
      });
    }

    this.confirmPasswordValidator = (control) => {
      if (!control.value) {
        return { error: true, required: true };
      } else if (control.value !== this.formGroup3.controls.passWord.value) {
        return { passWordTo: true, error: true };
      }
      return {};
    };

    this.formGroup3 = this.fb.group({
      passWord: [
        null,
        [
          Validators.required,
          Validators.maxLength(6),
          Validators.minLength(6),
          Validators.pattern('([\\d]){6,6}'),
          this.blurTestPw

        ],
      ],
      passWordTo: [null, [this.confirmPasswordValidator, Validators.required, Validators.maxLength(6), Validators.minLength(6)]],
      voucher: [null, [Validators.required]],
    });
  }

  initStep1SF() {
    this.step1Schema = {
      properties: {
        phone: {
          title: '手机号',
          type: 'string',
          ui: {
            widget: 'text',
            defaultText: this.phone.toString(),
          } as SFTextWidgetSchema,
        },
        smsVerifyCode: {
          type: 'string',
          title: '验证码',
          ui: {
            widget: 'custom',
            errors: {
              required: '请输入验证码',
            },
          } as SFTextareaWidgetSchema,
        },
      },
      required: ['smsVerifyCode'],
    };

    this.ui = {
      '*': { spanLabelFixed: 90, grid: { span: 16, gutter: 4 } },
    };
  }

  nextStep() {
    if (this.step1sf.valid) {
      this.service.request(this.service.$api_get_verifyPhone, this.step1sf.value).subscribe((res) => {
        if (res) {
          this.formGroup3.patchValue(res, { onlySelf: true });
          this.step = 1;
          this.count = 0;
          clearInterval(this.interval$);
        }
      });
    }
  }

  formSubmit() {
    for (const i in this.formGroup3.controls) {
      if (true) {
        this.formGroup3.controls[i].markAsDirty();
        this.formGroup3.controls[i].updateValueAndValidity();
      }
    }

    if (this.formGroup3.valid) {
      const param = Object.assign({}, this.formGroup3.value);
      this.service.http.post(this.service.$api_voucherUpdatePayPassword, param).subscribe((res) => {
        if (res.success === true) {
          this.step++;
          setTimeout(() => {
            // this.settingService.setUser({});
            // // 清空路由复用信息
            // this.reuseTabService.clear();
            // // 设置用户Token信息
            // this.tokenService.clear();
            this.router.navigate(['/account/center']);
          }, 3000);
        }
      });
    }
  }

  getMsgCode() {
    if (this.phone) {
      this.getCode(`${this.service.$api_get_msg_code}`);
    } else {
      this.service.request(this.service.$api_get_current_user_info).subscribe((res) => {
        this.phone = res.phone;
        this.getCode(`${this.service.$api_get_msg_code}`);
      });
    }
  }
  goBack() {
    window.history.go(-1);
  }
  getCode(url: string, params?: any) {
    this.service.http.post(url, null, params).subscribe((res) => {
      // code==503046 弹出网易盾
      if (res.success && res.data.code === '1') {
        this.service.msgSrv.success('发送成功');
        this.codeCountDown();
      } else if (res.data.code === '503046') {
        this.dun.popUp();
      } else {
        this.service.msgSrv.success(res.sendResult);
      }
    });
  }
  /* code倒计时 */
  codeCountDown() {
    this.count = 59;
    this.interval$ = setInterval(() => {
      this.count -= 1;
      if (this.count <= 0) {
        clearInterval(this.interval$);
      }
    }, 1000);
  }
  /* 网易盾验证通过 */
  captchaDone(validate: any) {
    this.codeCountDown();
  }

  validateConfirmPassword(): void {
    
    setTimeout(() => this.formGroup3.controls.passWordTo.updateValueAndValidity());
  }
  // blurTestPw(){
  //   const reg = /[^\d]/g
  //   const val: any = this.formGroup3.controls.passWord.value
  //   if(val.length === 6) {
  //     const pattern = /([\d])\1{2,}/g
  //     const pattern2 = /(?:(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){5}|(?:9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){5})\d/g   
  //     if(pattern.test(val) || pattern2.test(val)){
  //       return false
  //     } else {
  //       return true
  //     } 
  //   } else {
  //     return false
  //   }
  // }
  blurTestPw = (control: FormControl): { [s: string]: boolean } => {
    if (!control.value) {
      return { required: true };
    } else if (control.value.length === 6) {
      const pattern = /([\d])\1{2,}/g
      const pattern2 = /(?:(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){5}|(?:9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)|1(?=0)){5})\d/g   
      if(pattern.test(control.value) || pattern2.test(control.value)){
        return { confirm: true, error: true };
      }
    }
    return {};
  };
}
